package com.googlecode.cnasort.cc.rmi.common;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import org.apache.log4j.Logger;

/**
 * class to do some common things for client & server to get RMI working
 */
public abstract class RmiStarter<T extends Remote>
{
    private static final Logger logger = Logger.getLogger( RmiStarter.class );

    /**
     *
     * @param clazzToAddToServerCodebase a class that should be in the
     *        java.rmi.server.codebase property.
     * @throws CustomRmiHandlingException
     */
    public RmiStarter(
        final Class<T> clazzToAddToServerCodebase,
        final Integer  createServerRegistryPort
        )
    {
        System.setProperty(
            "java.rmi.server.codebase",
            clazzToAddToServerCodebase.getProtectionDomain().getCodeSource().getLocation().toString()
            );

        System.setProperty(
            "java.security.policy",
            PolicyFileLocator.getLocationOfPolicyFile()
            );

        if( createServerRegistryPort != null ) {
            try {
                LocateRegistry.createRegistry( createServerRegistryPort.intValue() );
                logger.info( "Server started" );
                }
            catch( RemoteException e ) {
                // ignore;
                logger.warn( "Server already started" );
                }
            }

        if( System.getSecurityManager() == null ) {
            System.setSecurityManager( new SecurityManager() );
            }
    }

    public RmiStarter(
        final Class<T> clazzToAddToServerCodebase,
        final boolean  createServerRegistryOnDefautPort
        )
    {
        this(
            clazzToAddToServerCodebase,
            createServerRegistryOnDefautPort ? new Integer( Registry.REGISTRY_PORT ) : null
            );
    }

    public RmiStarter(final Class<T> clazzToAddToServerCodebase )
    {
        this( clazzToAddToServerCodebase, null );
    }
}
